package cn.huijielong.modules.group.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.huijielong.common.utils.Query;
import cn.huijielong.modules.group.dao.GoodsDao;
import cn.huijielong.modules.group.dao.GroupDao;
import cn.huijielong.modules.group.entity.GoodsEntity;
import cn.huijielong.modules.group.entity.GroupEntity;
import cn.huijielong.modules.group.service.GoodsService;
import cn.huijielong.modules.group.service.GroupService;
import cn.huijielong.modules.group.service.OrderService;
import cn.huijielong.modules.sys.service.impl.SimpleServiceImpl;



@Service("groupService")
public class GroupServiceImpl extends SimpleServiceImpl implements GroupService {
	@Autowired
	private GroupDao groupDao;
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private OrderService orderService;
	@Autowired
	private GoodsService goodsService;
	
	@Override
	public GroupEntity queryObject(Long groupId){
		GroupEntity group = groupDao.queryObject(groupId);
		Query q=Query.empty();
		q.addParam("groupId", groupId);
		List<GoodsEntity> goodsList=goodsDao.queryList(q);
		group.setGoodsList(goodsList);
		
		group.setOrderList(orderService.queryListByGroup(groupId));
		return group;
	}
	
	@Override
	public Page<GroupEntity> queryList(Query q){
	    Page<GroupEntity> page=PageHelper.startPage(q.getPage(), q.getLimit()).doSelectPage(()-> groupDao.queryList(q));
		return page;		
	}
	
	@Transactional
	@Override
	public void save(GroupEntity group){
		
		groupDao.save(group);
		if(group.getGoodsList()!=null && group.getGoodsList().size()>0) {
			List<GoodsEntity> goodsList=group.getGoodsList();
			for(GoodsEntity goods:goodsList) {
				goods.setGroupId(group.getGroupId());
			}
			goodsService.save(goodsList);
		}
	}
	@Transactional
	@Override
	public void update(GroupEntity group){
		if(group.getLocationId()!=null && group.getLocationId()>0) {
			groupDao.update(group);
		}
		if(group.getGoodsList()!=null && group.getGoodsList().size()>0) {
			List<GoodsEntity> goodsList=group.getGoodsList();
			for(GoodsEntity goods:goodsList) {
				goods.setGroupId(group.getGroupId());
			}
			goodsService.update(goodsList);
		}
	}
	/**
	 * 上传团购图片
	 */
	@Transactional
	
	@Override
	public void delete(Long groupId){
		groupDao.delete(groupId);
	}

	@Override
	public Query queryCurGroupId(Long page) {
		return groupDao.queryCurGroupId(page);
	}
	
}
